#pragma once

#include "message.hpp"
#include <vector>
#include <assert.h>
#include <iostream>
#include <memory>
#include <sstream>
#include <utility>
#include <cstdlib>

namespace Log
{
    class FormatItem
    {
    public:
        using ptr = std::shared_ptr<FormatItem>;
        //virtual ~FormatItem() {}
        virtual void format(std::ostream &out, const LogMsg &msg) = 0;
    };

    class TimeFormatItem : public FormatItem
    {
    private:
        std::string _format; // 将时间戳转化成某种格式
    public:
        TimeFormatItem(const std::string &format = "%H:%M:%S") : _format(format)
        {
            if (format.empty())
                _format = "%H:%M:%S";
        }

        void format(std::ostream &out, const LogMsg &msg) override
        {
            time_t t = msg._ctime;
            struct tm lt;
            localtime_r(&t, &lt);
            char tmp[128];
            strftime(tmp, 127, _format.c_str(), &lt);
            out << tmp;
        }
    };

    class CFileFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._file;
        }
    };

    class LevelFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            // level是自定义类型，这里我们要自己实现一个tostring
            out << LogLevel::tostring(msg._level);
        }
    };

    class CLineFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._line;
        }
    };

    class NameFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._name;
        }
    };

    class MsgFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._payload;
        }
    };

    class ThreadFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._tid;
        }
    };

    class NlineFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\n";
        }
    };

    class TabFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\t";
        }
    };

    class OtherFormatItem : public FormatItem
    { // 输出任意用户定义的字符串（可能是空格、符号、固定文本等）。
    private:
        std::string _str;

    public:
        OtherFormatItem(std::string str = "") : _str(str) {}
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << _str;
        }
    };

    class Formatter
    {

        //  %d ⽇期
        //  %T 缩进
        //  %t 线程id
        //  %p ⽇志级别
        //  %c ⽇志器名称
        //  %f ⽂件名
        //  %l ⾏号
        //  %m ⽇志消息
        //  %n 换
    private:
        std::string _pattern;                // 自定义的格式化样式
        std::vector<FormatItem::ptr> _items; // 存储 实例化Item 的数组

    public:
        using ptr = std::shared_ptr<Formatter>;
        Formatter(const std::string pattern = "[%d{%H:%M:%S}][%t][%p][%c][%f:%l] %m%n")
            : _pattern(pattern)
        {
            assert(parsePattern());
        }

        void format(std::ostream &out, const LogMsg &msg)
        {
            for (auto &it : _items)
            {
                it->format(out, msg);
            }   
        }

        std::string format(const LogMsg &msg)
        {
            std::stringstream ss;
            format(ss,msg);
            return ss.str();
        }

        //  %d ⽇期
        //  %T 缩进
        //  %t 线程id
        //  %p ⽇志级别
        //  %c ⽇志器名称
        //  %f ⽂件名
        //  %l ⾏号
        //  %m ⽇志消息
        //  %n 换
        //"[%d{%H:%M:%S}][%t][%p][%c][%f:%l] %m%n"
        FormatItem::ptr CreateItem(const std::string &key, const std::string &val)
        {
            if (key == "d")
                return std::make_shared<TimeFormatItem>(val);
            if (key == "T")
                return std::make_shared<TabFormatItem>();
            if (key == "t")
                return std::make_shared<ThreadFormatItem>();
            if (key == "p")
                return std::make_shared<LevelFormatItem>();
            if (key == "c")
                return std::make_shared<NameFormatItem>();
            if (key == "f")
                return std::make_shared<CFileFormatItem>();
            if (key == "l")
                return std::make_shared<CLineFormatItem>();
            if (key == "m")
                return std::make_shared<MsgFormatItem>();
            if (key == "n")
                return std::make_shared<NlineFormatItem>();
            if (key == "")
                return std::make_shared<OtherFormatItem>(val);
            std::cerr << "未知的格式化字符%" << key << "!!!" << std::endl;
            abort();
        }

    private:
        // 解析pattern 是否合法性
        bool parsePattern()
        {
            std::vector<std::pair<std::string, std::string>> arry;
            std::string key, val;
            size_t pos = 0;
            while (pos < _pattern.size()) // abcsd%%asd[%d{%H:%M:%S}][%t][%p][%c][%f:%l]
            {
                // 如果_pattern[pos] 不是‘%’ 则这些字符都不是格式化字符
                if (_pattern[pos] != '%')
                {
                    val.push_back(_pattern[pos]);
                    pos++;
                    continue;
                }

                // 如果 _pattern[pos] == '%' 我们需要判断 是否是 '%%'
                if (pos + 1 < _pattern.size() && _pattern[pos + 1] == '%')
                {
                    val.push_back('%');
                    pos += 2;
                    continue;
                }

                // 将用户自定的非格式化字符插入到arry中
                if (!val.empty())
                {
                    arry.push_back(std::make_pair("", val));
                    val.clear(); // 清空val
                }

                // 如果是正常的格式化字符 我们需要判断是否存在子规则,%d{%H:%M:%S}
                pos++; // 这里指的是 % 之后的格式化字符
                if (pos == _pattern.size())
                {
                    std::cerr << "%之后缺少格式化字符！！！" << std::endl;
                    return false;
                }
                key.push_back(_pattern[pos]);
                pos++;
                if (pos < _pattern.size() && _pattern[pos] == '{')
                {
                    pos++;
                    while (pos < _pattern.size() && _pattern[pos] != '}')
                    {
                        val.push_back(_pattern[pos]);
                        pos++;
                    }
                    // while循环 可能因为 pos 越界而退出，所以我们需要判断
                    if (pos == _pattern.size())
                    {
                        std::cerr << "子规则'{}'匹配失败！！！" << std::endl;
                        return false;
                    }

                    pos++;
                }

                arry.push_back(std::make_pair(key, val));
                key.clear();
                val.clear();
            }

            for (auto &it : arry)
            {
                _items.push_back(CreateItem(it.first, it.second));
            }
            return true;
        }
    };

}